// HttpServer.hpp
#pragma once
#include <signal.h>
#include "TcpServer.hpp"
// #include "Protocol.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"

#define PORT 8080

class Connect;

class HttpServer
{
public:
    HttpServer(int port = PORT, int num = 5)
        : _port(port), _num(num), stop(false)
    {
    }
    ~HttpServer() {}
    void InitServer()
    {
        // SIGPIPE信号需要忽略，不然写入时可能直接崩溃
        signal(SIGPIPE, SIG_IGN);
        // _tcp_server = TcpServer::GetInstance(_port);
        // _thread_poll = ThreadPool::GetInstance(_num);
    }
    void Loop()
    {
        LOG(INFO, "Loop begin");
        // int listensock = _tcp_server->Sock();
        TcpServer *tsvr = TcpServer::GetInstance(_port);
        ThreadPool *tp = ThreadPool::GetInstance(_num);
        if (nullptr == tp)
            return;
        while (!stop)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // int sock = accept(listensock, (struct sockaddr *)&peer, &len);
            int sock = accept(tsvr->Sock(), (struct sockaddr *)&peer, &len);
            if (sock < 0)
            {
                LOG(ERROR, "accept error");
                continue;
            }
            LOG(INFO, "get a new link: " + std::to_string(sock));

            // Connect* conn = new Connect;
            // conn->sock = sock;
            // conn->port = ntohs(peer.sin_port);
            // char buffer[16];
            // inet_ntop(AF_INET, &peer.sin_addr, buffer, sizeof(buffer));
            // conn->ip = buffer;

            // pthread_t tid;
            // pthread_create(&tid, nullptr, Entrance::HandlerRequest, conn);
            // pthread_detach(tid);

            Task task(sock);
            tp->PushTask(task);
        }
    }

private:
    int _port;
    int _num; // 线程池线程个数
    // TcpServer *_tcp_server;
    // ThreadPool* _thread_poll;
    bool stop; // 服务器是否是正在运行的
};